<template>
  <div class="dashboard-container" v-if="isAdmin">
    <!-- 数据统计卡片 -->
    <el-row :gutter="20">
      <el-col :span="6">
        <el-card class="stat-card" shadow="hover" @click="handleTypeChange('users')">
          <div class="stat-content">
            <el-icon class="stat-icon">
              <User/>
            </el-icon>
            <div class="stat-info">
              <div class="label">用户数量</div>
              <div class="value">{{ stats.userCount }}</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card class="stat-card" shadow="hover" @click="handleTypeChange('schools')">
          <div class="stat-content">
            <el-icon class="stat-icon">
              <School/>
            </el-icon>
            <div class="stat-info">
              <div class="label">学校数量</div>
              <div class="value">{{ stats.schoolCount }}</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card class="stat-card" shadow="hover" @click="handleTypeChange('issues')">
          <div class="stat-content">
            <el-icon class="stat-icon">
              <Warning/>
            </el-icon>
            <div class="stat-info">
              <div class="label">问题数量</div>
              <div class="value">{{ stats.issueCount }}</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card class="stat-card" shadow="hover" @click="handleTypeChange('feedback')">
          <div class="stat-content">
            <el-icon class="stat-icon">
              <ChatLineRound/>
            </el-icon>
            <div class="stat-info">
              <div class="label">反馈数量</div>
              <div class="value">{{ stats.feedbackCount }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 将原有的提示信息移动到新的布局中 -->
    <el-row :gutter="20" class="chart-row">
      <!-- 图表区域 -->
      <el-col :span="16">
        <el-card class="chart-card" shadow="hover">
          <div class="chart-header">
            <h3>{{ chartTitle }}</h3>
          </div>
          <div class="chart-container">
            <v-chart class="chart" :option="chartOption" autoresize/>
          </div>
        </el-card>
      </el-col>

      <!-- 消息区域 -->
      <el-col :span="8">
        <el-card class="message-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>学校列表</span>
            </div>
          </template>
          
          <el-collapse v-model="activeSchools" accordion >
            <el-collapse-item 
              v-for="school in schoolList" 
              :key="school.schoolId"
              :title="school.schoolName"
              :name="school.schoolId"
            >
              <div class="school-info">
                <div class="info-item">
                  <span class="label">问题总数：</span>
                  <span class="value">{{ school.issueCount }}</span>
                </div>
                <div class="info-item">
                  <span class="label">待处理：</span>
                  <span class="value">{{ school.pendingCount }}</span>
                </div>
                <div class="info-item">
                  <span class="label">已处理：</span>
                  <span class="value">{{ school.resolvedCount }}</span>
                </div>
              </div>
            </el-collapse-item>
          </el-collapse>
        </el-card>
      </el-col>
    </el-row>
  </div>
  <div v-if="isSchool">
    <div class="statistics-container">
      <!-- 第一行统计卡片 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-title">总问题数量</div>
              <div class="stat-number">{{ totalIssues }}</div>
              <el-icon class="stat-icon"><Document /></el-icon>
            </div>
          </el-card>
        </el-col>
        
        <el-col :span="8">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-title">已解决问题</div>
              <div class="stat-number">{{ solvedIssues }}</div>
              <el-icon class="stat-icon"><CircleCheck /></el-icon>
            </div>
          </el-card>
        </el-col>
        
        <el-col :span="8">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-title">未解决问题</div>
              <div class="stat-number">{{ unsolvedIssues }}</div>
              <el-icon class="stat-icon"><Warning /></el-icon>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 第二行统计卡片 -->
      <el-row :gutter="20" style="margin-top: 20px;">
        <el-col :span="8">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-title">今日新增</div>
              <div class="stat-number">{{ todayNewIssues }}</div>
              <el-icon class="stat-icon"><Plus /></el-icon>
            </div>
          </el-card>
        </el-col>

        <el-col :span="8">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-title">今日已处理</div>
              <div class="stat-number">{{ todaySolvedIssues }}</div>
              <el-icon class="stat-icon"><Check /></el-icon>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 添加问题类型统计卡片 -->
      <el-row :gutter="20" class="issue-types-row">
        <el-col :span="24">
          <el-card class="issue-types-card">
            <template #header>
              <div class="card-header">
                <span>问题类型统计</span>
              </div>
            </template>
            <el-row :gutter="20">
              <el-col :span="8" v-for="(count, type) in issueTypes" :key="type">
                <div class="issue-type-item">
                  <el-card shadow="hover">
                    <div class="type-content">
                      <div class="type-icon">
                        <el-icon><Document /></el-icon>
                      </div>
                      <div class="type-info">
                        <div class="type-name">{{ type }}</div>
                        <div class="type-count">{{ count }} 个问题</div>
                      </div>
                    </div>
                  </el-card>
                </div>
              </el-col>
            </el-row>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, reactive } from 'vue'
import { User, School, Warning, ChatLineRound, Document, CircleCheck, Plus, Check } from '@element-plus/icons-vue'
import VChart from 'vue-echarts'
import { use } from 'echarts/core'
import { LineChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
import request from '@/utils/request'
import { ElMessage } from 'element-plus'
import {getInfo} from "@/api/login.js";
import Hour from "@/components/Crontab/hour.vue";

// 注册必须的组件
use([
  CanvasRenderer,
  LineChart,
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent
])

// 添加 loading 状态
const loading = ref(false)

const schoolList = ref([])

const userRole = ref([])

// 数据相关的状态
const stats = ref({
  userCount: 0,
  schoolCount: 0,
  issueCount: 0,
  feedbackCount: 0,
  pendingIssues: 0,
  newFeedbacks: 0
})

// 图表数据结构
const historicalData = reactive({
  users: {
    dates: [],
    values: []
  },
  schools: {
    dates: [],
    values: []
  },
  issues: {
    dates: [],
    values: []
  },
  feedback: {
    dates: [],
    values: []
  }
})

// 从后端获取统计数据和图表数据
const loadDashboardData = async () => {
  try {
    loading.value = true;
    const response = await request({
      url: '/system/dashboard/data',
      method: 'get'
    });

    if (response.code === 200) {
      const { stats: fetchedStats, chartData } = response.data;
      
      // 更新统计数据
      stats.value = fetchedStats;
      
      // 更新图表数据
      Object.keys(chartData).forEach(key => {
        if (historicalData[key]) {
          historicalData[key].dates = chartData[key].dates;
          historicalData[key].values = chartData[key].values;
        }
      });
    } else {
      ElMessage.error(response.msg || '获取数据失败');
    }
  } catch (error) {
    console.error('获取仪表板数据失败:', error);
    ElMessage.error('获取数据失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

const loadSchoolList = async () => {
  try {
    loading.value = true;
    const response = await request({
      url: '/system/dashboard/schoolList',
      method: 'get'
    });

    if (response.code === 200) {
      schoolList.value = response.data;
    } else {
      ElMessage.error(response.msg || '获取学校列表失败');
    }
  } catch (error) {
    console.error('获取学校列表失败:', error);
  }
}

const isAdmin = ref(false);
const isSchool = ref(false);

// 在组件挂载时加载数据
onMounted(async () => {
  await getInfo().then(res => {
    userRole.value = res.roles[0] || '';
    if (userRole.value === 'admin'|| userRole.value === 'education') {
      loadDashboardData();
      loadSchoolList();
      isAdmin.value = true;
    } else if (userRole.value === 'school') {
      isSchool.value = true;
      loadSchoolDashboardData(); // 加载学校仪表板数据
    }
  });
});

// 图表相关的状态
const currentType = ref('users')
const chartTitle = computed(() => {
  const titles = {
    users: '用户数量趋势',
    schools: '学校数量趋势',
    issues: '问题数量趋势',
    feedback: '反馈数量趋势'
  }
  return titles[currentType.value]
})

const chartOption = computed(() => ({
  title: {
    text: chartTitle.value,
    left: 'center',
  },
  tooltip: {
    trigger: 'axis',
  },
  xAxis: {
    type: 'category', // 类目轴
    data: historicalData[currentType.value]?.dates || [], // 防止数据为空
    axisLabel: {
      rotate: 45, // 标签旋转角度
    },
  },
  yAxis: {
    type: 'value', // 数值轴
  },
  series: [
    {
      data: historicalData[currentType.value]?.values || [], // 数据
      type: 'line', // 折线图类型
      smooth: true, // 平滑曲线
      showSymbol: true, // 显示拐点
      symbolSize: 8, // 拐点大小
      lineStyle: {
        width: 3,
        color: '#0B7E99', // 替换为具体颜色值
      },
      itemStyle: {
        color: '#0B7E99', // 替换为具体颜色值
      },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            {offset: 0, color: '#0B7E99'}, // 渐变起始颜色
            {offset: 1, color: '#ffffff'}, // 渐变结束颜色
          ],
        },
      },
    },
  ],
}));


// 处理图表类型切换
const handleTypeChange = (type) => {
  currentType.value = type
}

const totalIssues = ref(0)
const solvedIssues = ref(0)
const unsolvedIssues = ref(0)
const issueTypes = ref({})

// 添加新的响应式变量
const todayNewIssues = ref(0)
const todaySolvedIssues = ref(0)

// 修改数据获取函数
const loadSchoolDashboardData = async () => {
  if (isSchool.value) {
    try {
      const response = await request({
        url: '/system/dashboard/schoolData',
        method: 'get'
      })
      
      if (response.code === 200) {
        const data = response.data
        // 更新基础统计数据
        totalIssues.value = data.total
        solvedIssues.value = data.solved
        unsolvedIssues.value = data.unsolved
        todayNewIssues.value = data.todayNew || 0
        todaySolvedIssues.value = data.todaySolved || 0
        
        // 将数组格式转换为对象格式
        const typesObj = {}
        data.issueTypes.forEach(item => {
          Object.assign(typesObj, item)
        })
        issueTypes.value = typesObj
      } else {
        ElMessage.error(response.msg || '获取统计数据失败')
      }
    } catch (error) {
      console.error('获取学校数据失败:', error)
      ElMessage.error('获取统计数据失败')
    }
  }
}

</script>

<style lang="scss" scoped>
.dashboard-container {
  padding: 20px;

  .stat-card {
    .stat-content {
      display: flex;
      align-items: center;

      .stat-icon {
        font-size: 48px;
        margin-right: 20px;
        color: var(--el-color-primary);
        transition: all 0.3s ease;

        &:hover {
          transform: scale(1.2) rotate(12deg);
          filter: drop-shadow(0 0 8px var(--el-color-primary-light-5));
        }
      }

      &:hover {
        .stat-icon {
          animation: iconFloat 1.5s ease-in-out infinite;
        }
      }

      .stat-info {
        .label {
          font-size: 14px;
          color: var(--el-text-color-secondary);
          margin-bottom: 8px;
        }

        .value {
          font-size: 24px;
          font-weight: bold;
          color: var(--el-text-color-primary);
        }
      }
    }
  }

  .notification-card {
    margin-top: 20px;

    .notification-item {
      margin-bottom: 10px;

      &:last-child {
        margin-bottom: 0;
      }
    }
  }
}

@keyframes iconFloat {
  0% {
    transform: translateY(0px);
  }
  50% {
    transform: translateY(-6px);
  }
  100% {
    transform: translateY(0px);
  }
}

.chart-card {
  margin-top: 20px;

  .chart-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 0 20px;

    h3 {
      margin: 0;
      font-size: 18px;
      color: var(--el-text-color-primary);
    }
  }

  .chart-container {
    padding: 0 20px;
  }

  .chart {
    height: 400px;
    width: 100%;
  }
}

.stat-card {
  cursor: pointer;
  transition: transform 0.3s ease;

  &:hover {
    transform: translateY(-5px);
  }

  &.active {
    border: 2px solid var(--el-color-primary);
  }
}

.chart-row {
  margin-top: 20px;
}

.message-card {
  height: 100%; // 确保消息卡片和图表卡片等高

  .card-header {
    font-weight: bold;
    color: var(--el-text-color-primary);
  }

  .message-list {
    margin-top: 20px;

    .message-item {
      display: flex;
      align-items: center;
      padding: 12px 0;
      border-bottom: 1px solid var(--el-border-color-lighter);

      &:last-child {
        border-bottom: none;
      }

      .message-icon {
        font-size: 20px;
        color: var(--el-color-primary);
        margin-right: 12px;
      }

      .message-content {
        flex: 1;

        .message-title {
          font-size: 14px;
          color: var(--el-text-color-primary);
          margin-bottom: 4px;
        }

        .message-time {
          font-size: 12px;
          color: var(--el-text-color-secondary);
        }
      }
    }
  }

  .notification-item {
    margin-bottom: 10px;
  }
}

// 调整图表卡片样式
.chart-card {
  margin-top: 0; // 移除原有的上边距，因为现在用 row 的 margin 控制
}

.statistics-container {
  padding: 20px;
}

.stat-card {
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
}

.stat-content {
  position: relative;
  padding: 20px;
}

.stat-title {
  font-size: 16px;
  color: #606266;
  margin-bottom: 10px;
}

.stat-number {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
}

.stat-icon {
  position: absolute;
  right: 20px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 40px;
  color: #409EFF;
  opacity: 0.3;
}

.issue-types-row {
  margin-top: 20px;
}

.issue-types-card {
  .card-header {
    font-weight: bold;
    font-size: 16px;
  }
}

.issue-type-item {
  margin-bottom: 20px;
  
  .el-card {
    height: 100%;
  }

  .type-content {
    display: flex;
    align-items: center;
    padding: 10px;
  }

  .type-icon {
    font-size: 24px;
    color: var(--el-color-primary);
    margin-right: 15px;
  }

  .type-info {
    flex: 1;
    
    .type-name {
      font-size: 16px;
      color: var(--el-text-color-primary);
      margin-bottom: 5px;
    }

    .type-count {
      font-size: 14px;
      color: var(--el-text-color-secondary);
    }
  }
}
</style>
